﻿using PLCS.Domain.Shared.Tasks;
using PLCS.Domain.Tasks;
using PLCS.EquipmentService.Methods;

namespace PLCS.Web.EventHandlers.TaskFinshed;

public class DeleteTaskAndSaveToHistoryEventHandler : ILocalEventHandler<TaskFinshEvent>, ITransientDependency
{
    private readonly ITaskRepository _taskRepository;
    private readonly IHisTaskRepository _hisTaskRepository;
    private readonly IInstructionRepository _instructionRepository;
    private readonly ILogger<DeleteTaskAndSaveToHistoryEventHandler> _logger;
    private readonly ExecuteMethod _executeMethod;

    public DeleteTaskAndSaveToHistoryEventHandler(ITaskRepository taskRepository,
                             IHisTaskRepository hisTaskRepository,
                             IInstructionRepository instructionRepository,
                             ILogger<DeleteTaskAndSaveToHistoryEventHandler> logger,
                             ExecuteMethod executeMethod)
    {
        _taskRepository = taskRepository;
        _hisTaskRepository = hisTaskRepository;
        _instructionRepository = instructionRepository;
        _logger = logger;
        _executeMethod = executeMethod;
    }

    public async Task HandleEventAsync(TaskFinshEvent eventData)
    {
        await _taskRepository.DeleteAsync(eventData.Id);
        var hisTask = new HisTask(eventData.TaskId,
                                  eventData.Level,
                                  eventData.TrayType,
                                  eventData.CreationTime,
                                  eventData.TaskType,
                                  eventData.TaskSource,
                                  eventData.StartPos,
                                  eventData.EndPos,
                                  eventData.OrderNo,
                                  eventData.BeforeExecutionMethod,
                                  eventData.BeforeExecutionParam,
                                  eventData.AfterExecutionMethod,
                                  eventData.AfterExecutionParam,
                                  eventData.TaskId_Higher);
        await _hisTaskRepository.InsertAsync(hisTask);
        _logger.LogInformation($"任务'{eventData.TaskId}'执行完成，从当前任务表中成功，存入任务任务表中");

        #region 如果有任务完成后执行事件，则执行方法

        if (!string.IsNullOrEmpty(eventData.AfterExecutionMethod))
            _executeMethod.ExecuteTriggerMethod("AfterExecutionMethod", eventData.AfterExecutionMethod, eventData.AfterExecutionParam);

        #endregion 如果有任务完成后执行事件，则执行方法
    }
}